package com.cdream.basic.thread;

import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cdream
 * @date 2021/9/12
 */
@Slf4j(topic = "volatile")
public class VolatileExample {
    private static boolean stop = false;
    private volatile static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        // testStop();
        // testRace();
        // Thread t1 = new Thread(() -> {
        //     for (int i = 0; i < 5000; i++) {
        //         count++;
        //     }
        // });
        // Thread t2 = new Thread(() -> {
        //     for (int i = 0; i < 5000; i++) {
        //         count--;
        //     }
        // });
        // t1.start();
        // t2.start();
        // t1.join();
        // t2.join();
        // System.out.println(count);
        new Thread(()-> {
            while (!stop){
                int res = 0;
                for (int i = 0; i < 10000000; i++) {
                    res++;
                }
                // log.debug("123123");
                // try {
                //     // Thread.sleep(1);
                // } catch (InterruptedException e) {
                //     e.printStackTrace();
                // }
            }
            log.debug("停下了");
        },"t1").start();
        Thread.sleep(1000);
        stop = true;
    }

    private static void testRace() throws InterruptedException {
        Room room = new Room();
        System.out.println(room.getCount());
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.increase();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5001; i++) {
                room.decrease();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(room.getCount()+1);
    }

    private static void testStop() {
        new Thread(() -> {
            while (!stop) {
            }
        }).start();
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                stop = true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


}
@ToString
class Dog {
    String name;
    String age;

    public Dog(String name, String age) {
        this.name = name;
        this.age = age;
    }

}

class Room {
    private volatile int count = 0;

    public void increase(){
        synchronized (this){
            count++;
        }
    }
    public void decrease(){
        synchronized (this){
            count--;
        }
    }
    public int getCount(){
        return this.count;
    }
}
